//
//  THLookVideoCommentViewController.m
//  TreeHole
//
//  Created by apple on 2020/9/19.
//  Copyright © 2020 stoneobs. All rights reserved.
//

#import "THLookVideoCommentViewController.h"

@interface THLookVideoCommentViewController ()<UITableViewDelegate,UITableViewDataSource>
@property(nonatomic, strong) STButton                     *stoneobs_ui_clearButton;
@property(nonatomic, strong) UIView                     *stoneobs_ui_customView;
@property(nonatomic, strong) UITableView                     *tableView;/**<  */
@property(nonatomic, strong) NSMutableArray                     *dataSouce;/**<  */
@property(nonatomic, assign) NSInteger                       page;/**<  */
@end

@implementation THLookVideoCommentViewController

- (instancetype)init
{
    if (self == [super init]) {
        self.modalPresentationStyle = UIModalPresentationOverFullScreen;
    }
    return self;
}
#pragma mark --vc 生命周期
- (void)viewDidLoad{
    [super viewDidLoad];
    [self stoneobs_ui_configSubView];
    __weak typeof(self) weakSelf =  self;
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        weakSelf.page = 1;
        [weakSelf stoneobs_fun_st_send_list_request];
    }];
    weakSelf.page = 1;
    [weakSelf stoneobs_fun_st_send_list_request];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
}
- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    [self stoneobs_fun_show];
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
}
- (void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
}
#pragma mark --subView
- (void)stoneobs_ui_configSubView{
    self.view.backgroundColor = UIColor.clearColor;
    __weak typeof(self) weakSelf =  self;
    self.stoneobs_ui_clearButton = [[STButton alloc] initWithFrame:STONEOBS_UI_UISCREEN_FRAME
                                                             title:nil
                                                        titleColor:nil
                                                         titleFont:0
                                                      cornerRadius:0
                                                   backgroundColor:[[UIColor blackColor] colorWithAlphaComponent:0.4]
                                                   backgroundImage:nil
                                                             image:nil];
    [weakSelf.stoneobs_ui_clearButton setClicAction:^(UIButton *sender) {
        
    }];
    [self.view addSubview:_stoneobs_ui_clearButton];
    
    self.stoneobs_ui_customView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, UISCREEN_WIDTH, UISCREEN_HEIGHT * 0.6)];
    self.stoneobs_ui_customView.centerX = UISCREEN_WIDTH / 2;
    self.stoneobs_ui_customView.top = UISCREEN_HEIGHT;
    self.stoneobs_ui_customView.backgroundColor = [UIColor whiteColor];
    self.stoneobs_ui_customView.layer.cornerRadius = 10;
    self.stoneobs_ui_customView.clipsToBounds = YES;
    [self.view addSubview:self.stoneobs_ui_customView];
    
    STLabel * stoneobs_ui_label = [[STLabel alloc] initWithFrame:CGRectMake(0, 10, UISCREEN_WIDTH, 44)
                                                            text:[NSString stringWithFormat:@"%@条评论",@(self.model.comment_num)]
                                                       textColor:STONEOBS_UI_FIRST_TEXT_COLOR
                                                            font:15
                                                     isSizetoFit:NO
                                                   textAlignment:NSTextAlignmentCenter];
    [self.stoneobs_ui_customView addSubview:stoneobs_ui_label];
    
    STButton * closebutton = [[STButton alloc] initWithFrame:CGRectMake(0, 10, 44, 44)
                                                       title:nil
                                                  titleColor:nil
                                                   titleFont:0
                                                cornerRadius:0
                                             backgroundColor:nil
                                             backgroundImage:nil
                                                       image:[UIImage imageNamed:@"关闭"]];
    closebutton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    closebutton.right = UISCREEN_WIDTH  - 5;
    [closebutton setClicAction:^(UIButton *sender) {
        [weakSelf stoneobs_fun_dismiss];
    }];
    [self.stoneobs_ui_customView addSubview:closebutton];
    
    
    STButton * stoneobs_ui_button = [[STButton alloc] initWithFrame:CGRectMake(15, 0, UISCREEN_WIDTH-30, 42)
                                                              title:@"说点什么吧"
                                                         titleColor:WH_UICOLOR_FROM_RGBA(0x9A9A9A)
                                                          titleFont:15
                                                       cornerRadius:21
                                                    backgroundColor:UIColor.whiteColor
                                                    backgroundImage:nil
                                                              image:nil];
    stoneobs_ui_button.titleEdgeInsets = UIEdgeInsetsMake(0, 5, 0, 0);
    [stoneobs_ui_button stbw_setBorderWith:1 borderColor:[WH_UICOLOR_FROM_RGBA(0xDADADA) colorWithAlphaComponent:0.35] cornerRadius:21];
    stoneobs_ui_button.titleEdgeInsets = UIEdgeInsetsMake(0, 15, 0, 0);
    [self.stoneobs_ui_customView addSubview:stoneobs_ui_button];
    [stoneobs_ui_button setClicAction:^(UIButton *sender) {
        
        THAddCommentPresentViewController * vc  = THAddCommentPresentViewController.new;
        [vc setDidFillComment:^(NSString * _Nonnull comment) {
            [THTreeHoleDataController addcommentFormPosts_id:self.model.t_id content:comment handle:^(NSError *error, BOOL success, NSDictionary *resp) {
                
                if (success) {
                    if (weakSelf.didComment) {
                        weakSelf.didComment();
                    }
                    [weakSelf stoneobs_fun_dismiss];
                }
            }];
        }];
        [weakSelf presentViewController:vc animated:NO completion:nil];
    }];
    
    stoneobs_ui_button.bottom = self.stoneobs_ui_customView.height - 10;
    if (@available(iOS 11.0, *)) {
        stoneobs_ui_button.bottom = stoneobs_ui_button.bottom - UIApplication.sharedApplication.delegate.window.safeAreaInsets.bottom;
    } else {
        // Fallback on earlier versions
    }
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 54, UISCREEN_WIDTH, stoneobs_ui_button.top - 54) style:UITableViewStyleGrouped];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
    self.tableView.backgroundColor = UIColor.whiteColor;
    self.tableView.estimatedRowHeight = 0;
    self.tableView.estimatedSectionHeaderHeight = 0;
    self.tableView.estimatedSectionFooterHeight = 0;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.stoneobs_ui_customView addSubview:self.tableView];
    
    
    self.stoneobs_ui_customView.top = UISCREEN_HEIGHT;
    
    
}

- (void)stoneobs_fun_show{
    [UIView animateWithDuration:0.6
                          delay:0
         usingSpringWithDamping:0.6
          initialSpringVelocity:0.7
                        options:UIViewAnimationOptionLayoutSubviews
                     animations:^{
        self.stoneobs_ui_customView.bottom = UISCREEN_HEIGHT;
    } completion:^(BOOL finished) {
        
    }];
}
- (void)stoneobs_fun_dismiss{
    [self.view endEditing:YES];
    [UIView animateWithDuration:0.25 animations:^{
        self.stoneobs_ui_customView.top = UISCREEN_HEIGHT;
        self.stoneobs_ui_clearButton.alpha = 0;
    } completion:^(BOOL finished) {
        [self dismissViewControllerAnimated:NO completion:nil];
    }];
}
- (void)stoneobs_fun_dismissWithHandle:(void(^)(void))handle{
    [self.view endEditing:YES];
    [UIView animateWithDuration:0.25 animations:^{
        self.stoneobs_ui_customView.top = UISCREEN_HEIGHT;
        self.stoneobs_ui_clearButton.alpha = 0;
    } completion:^(BOOL finished) {
        [self dismissViewControllerAnimated:NO completion:^{
            if (handle) {
                handle();
            }
        }];
    }];
}
#pragma --mark UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.dataSouce.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    THTieZiCommentModel * model = self.dataSouce[indexPath.row];
    if (model.cus_height < 10) {
        [self tableView:tableView cellForRowAtIndexPath:indexPath];
    }
    return model.cus_height;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return 0.01;
}
- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString * reuseIdentifier =  @"cell";
    THTieZICommentTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
    if (!cell) {
        cell = [[THTieZICommentTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuseIdentifier];
        
    }
    THTieZiCommentModel * model = self.dataSouce[indexPath.row];
    cell.model = model;
    return cell;
}
#pragma --mark UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    THTieZiCommentModel * model = self.dataSouce[indexPath.row];
    [self stoneobs_fun_dismissWithHandle:^{
        [TMUtils goto_user_info_witdh_id:model.user_id];
    }];
    [self.tableView deselectRowAtIndexPath:indexPath animated:NO];
}
- (void)config_table_footer{
    __weak typeof(self) weakSelf =  self;
    self.tableView.mj_footer = [MJRefreshFooter footerWithRefreshingBlock:^{
        weakSelf.page ++;
        [weakSelf stoneobs_fun_st_send_list_request];
    }];
    
}
#pragma mark --stoneobs_net netWork Method
- (void)stoneobs_fun_st_send_list_request{
    NSMutableDictionary * stoneobs_net_param_dic = [NSMutableDictionary new];
    NSString * stoneobs_net_user_id = [STTools_UserManger defult].stoneobs_fun_get_loginedUser.uid.description;
    NSString * stoneobs_net_user_token = STTools_UserManger.defult.stoneobs_fun_get_loginedUser.token;
    if (stoneobs_net_user_id.length) {
        [stoneobs_net_param_dic setObject:stoneobs_net_user_id forKey:@"uid"];
    }
    if (stoneobs_net_user_token.length) {
        [stoneobs_net_param_dic setObject:stoneobs_net_user_token forKey:@"token"];
    }
    [stoneobs_net_param_dic setObject:@(self.page) forKey:@"page"];
    [stoneobs_net_param_dic setObject:self.model.t_id forKey:@"id"];
    NSString * stoneobs_net_net_url = [NSString stringWithFormat:@"%@%@",RELEASE_SERVER_URL_HEADER,@"v1/posts/comments"];
    DDLogInfo(@"url:%@",stoneobs_net_net_url);
    DDLogInfo(@"param:%@",stoneobs_net_param_dic);
    [[STTools_NetWrokManger defaultClient] stoneobs_fun_requestWithPath:stoneobs_net_net_url
                                                                 method:STHttpRequestType_stoneobs_enumGet
                                                             parameters:stoneobs_net_param_dic
                                                                success:^(NSURLSessionDataTask *operation, id responseObject) {
        [SVProgressHUD dismiss];
        NSDictionary * dic = [responseObject valueForKey:@"data"];
        NSArray * array = dic[@"items"];
        NSArray * objArray = [THTieZiCommentModel mj_objectArrayWithKeyValuesArray:array];
        NSInteger total = [dic[@"total"] integerValue];//总数量
        CGFloat perPage = [dic[@"perPage"] floatValue];
        CGFloat allpage = total / perPage; ;
        if (self.page == 1) {
            self.dataSouce = objArray.mutableCopy;
            [self.tableView reloadData];
            if (allpage>1) {
                [self config_table_footer];
            }
        }else{
            if (self.page < allpage) {
                [self.tableView.mj_footer endRefreshing];
            }else{
                [self.tableView.mj_footer endRefreshingWithNoMoreData];
            }
            [self.dataSouce addObjectsFromArray:objArray];
            [self.tableView reloadData];
        }
        [self config_table_footer];
        [self.tableView.mj_header endRefreshing];
        
        
    } failure:^(NSString *stateCode, STTools_Error *error,NSError *originError) {
        [SVProgressHUD dismiss];
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
        DDLogError(@"\n请求失败:\nurl:%@\nparam:%@\n失败原因:%@\n错误码:%ld",
                   stoneobs_net_net_url,stoneobs_net_param_dic,error.desc,error.code);
    }];
}
@end
